package com.itheima.chapter07.service;

import com.itheima.chapter07.domain.Authority;
import com.itheima.chapter07.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private CustomerService customerService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Customer customer = customerService.getCustomer(username);
        if (customer == null) {
            throw new UsernameNotFoundException("当前用户不存在");
        }

        List<Authority> authorities = customerService.getCustomerAuthority(username);

//        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
//        for (Authority authority : authorities) {
//            SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getAuthority());
//            grantedAuthorities.add(grantedAuthority);
//        }
        List<SimpleGrantedAuthority> list = authorities.stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
                .collect(Collectors.toList());
        UserDetails userDetails = new User(customer.getUsername(), customer.getPassword(), list);
        return userDetails;
    }
}
